/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package tk.eigh.ksvg.renderer.text;

import java.io.IOException;
import java.util.logging.Level;
import javax.faces.component.UIComponent;
import javax.faces.component.UIMessage;
import javax.faces.context.FacesContext;
import javax.faces.context.ResponseWriter;
import ksvg.text.TextRef;
import org.apache.myfaces.buildtools.maven2.plugin.builder.annotation.JSFRenderer;
import org.apache.myfaces.shared.renderkit.JSFAttr;
import org.apache.myfaces.shared.renderkit.html.HtmlRendererUtils;
import tk.eigh.ksvg.SVG;
import tk.eigh.ksvg.renderer.SVGRenderer;
import tk.eigh.ksvg.renderer.SVGRendererUtils;

/**
 *
 * @author nt
 */
@JSFRenderer(renderKitId = "SVG", type = "SVGTextRefRenderer", family = "text.TextRef")
public class SVGTextRefRenderer extends SVGRenderer {

    protected final static String TAG_NAME = "tref";

    @Override
    public void encodeBegin(FacesContext context, UIComponent component) throws IOException {
        super.encodeBegin(context, component);
        ResponseWriter writer = context.getResponseWriter();
        writer.startElement(TAG_NAME, component);
        renderCommonAttributes(writer, component, context);
        SVGRendererUtils.renderImplementedAttributes(component, writer);
        String forAttr = getFor(component);
        if (forAttr == null) {
            LOGGER.severe("Attribute 'for' of TextRef must not be null");
            return;
        }
        TextRef textref = (TextRef) component;
        UIComponent forComponent = context.getViewRoot().findComponent(forAttr);
        if (forComponent == null) {
            LOGGER.log(Level.SEVERE,
                    "Could not render tref. Unable to find component ''{0}'' (calling findComponent on component ''{1}"
                    + "''). If the provided id was correct, declare an id attribute on the defs element",
                    new Object[]{forAttr, textref.getClientId(context)});
            return;
        }
        String clientId = forComponent.getClientId(context);
        writer.writeAttribute(SVG.XLINK_HREF_ATTR, "#".concat(clientId), JSFAttr.FOR_ATTR);
    }

    @Override
    public void encodeEnd(FacesContext context, UIComponent component) throws IOException {
        super.encodeEnd(context, component);
        context.getResponseWriter().endElement(TAG_NAME);
    }

    protected String getFor(UIComponent component) {
        if (component instanceof TextRef) {
            return ((TextRef) component).getFor();
        }
        return (String) component.getAttributes().get(JSFAttr.FOR_ATTR);
    }
}
